package com.futvan.z.framework.util.enums;

import com.futvan.z.erp.customer.crm_customer;
import com.futvan.z.framework.core.z;
import com.futvan.z.framework.util.HttpUtil;
import com.futvan.z.framework.util.JsonUtil;
import com.futvan.z.framework.util.StringUtil;

import java.security.MessageDigest;
import java.util.*;

public class ZxUtil {


    /**
     * 发送客户信息给直销结算系统
     * @param type   0:新增客户  1:普通变更客户信息  2：账号绑定人更换  3：升级成为经销商  4:删除客户  5:换主号
     */
    public static void SendCustomerToZX(String type, crm_customer c){
        if(z.isNotNull(z.sp.get("zx_url"))){
            if(z.isNotNull(type)){
                if("0".equals(type) || "1".equals(type) || "2".equals(type) || "3".equals(type)|| "4".equals(type) || "5".equals(type)){
                    if(z.isNotNull(c)){
                        String customer_json = StringUtil.UrlEncode(JsonUtil.getJson(c));
                        HashMap<String,String> map = new HashMap<String,String>();
                        map.put("type",type);
                        map.put("customer",customer_json);
                        String sign = buildSign(map,z.sp.get("zx_service_key"),"utf-8");
                        String zx_url = z.sp.get("zx_url") +"api/updateCustomer?_sign="+sign+"&type="+ type +"&customer="+customer_json;
                        Thread thread = new Thread(new Runnable() {
                            @Override
                            public void run() {
                                try {
                                    String msg = HttpUtil.doGet(zx_url,null);
                                    z.Log("发送客户信息给直销结算系统|"+msg);
                                }catch (Exception e){
                                    z.Error("发送客户信息给直销结算系统出错|URL:"+zx_url,e);
                                }
                            }
                        });
                        thread.start();
                    }else{
                        z.Error("发送客户信息给直销结算系统出错|crm_customer is null");
                    }
                }else{
                    z.Error("发送客户信息给直销结算系统出错|type类型异常，只能是0、1、2、3、4、5|当前数据为："+type);
                }
            }else{
                z.Error("发送客户信息给直销结算系统出错|type is null");
            }
        }else{
            z.Error("发送客户信息给直销结算系统出错|zx_url is null");
        }
    }


    public static String buildSign(Map<String, String> dicArray, String key, String _input_charset) {
        List<String> list = mapSortByKey(dicArray);
        StringBuilder prestr = new StringBuilder();
        for (String name : list) {
            if (name.startsWith("_"))
                continue;
            String value = dicArray.get(name);
            if (value == null || value.isEmpty())
                continue;
            prestr.append("&" + name + "=" + value);
        }
        prestr.delete(0, 1);
        // 把拼接后的字符串再与安全校验码直接连接起来
        String mysign = md5(prestr.toString() + key, _input_charset); // 把最终的字符串签名，获得签名结果

        return mysign;
    }

    public static List<String> mapSortByKey(Map<String, String> unsort_map) {
        List<String> result = new ArrayList<String>();

        String[] unsort_key = new String[unsort_map.size()];

        unsort_map.keySet().toArray(unsort_key);

        Arrays.sort(unsort_key, new Comparator<String>() {
            public int compare(String o1, String o2) {
                return o1.toLowerCase().compareTo(o2.toLowerCase());
            }
        });

        for (int i = 0; i < unsort_key.length; i++) {
            result.add(unsort_key[i]);
        }
        return result;
    }


    /**
     * MD5加密
     *
     * @param s
     * @param charset
     * @return
     */
    public final static String md5(String s, String charset) {
        // 16进制下数字到字符的映射数组
        char hexDigits[] = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
                'a', 'b', 'c', 'd', 'e', 'f' };
        try {
            byte[] strTemp = s.getBytes(charset);
            MessageDigest mdTemp = MessageDigest.getInstance("MD5");
            mdTemp.update(strTemp);
            byte[] md = mdTemp.digest();
            int j = md.length;
            char str[] = new char[j * 2];
            int k = 0;
            for (int i = 0; i < j; i++) {
                byte byte0 = md[i];
                str[k++] = hexDigits[byte0 >>> 4 & 0xf];
                str[k++] = hexDigits[byte0 & 0xf];
            }
            return new String(str);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }
}
